﻿#region Using

using System;
using WSMon.Core.Configuration;
using WSMon.Core.Interfaces;
using System.Data.SqlClient;

#endregion

namespace WSMon.Core.Checkers.Database
{
    public class MsSqlChecker : Checker, IChecker
    {
        private readonly MsSqlConfigration _msSqlConfigration;
        private string _logs = string.Empty;

        public MsSqlChecker(MsSqlConfigration msSqlConfigration)
        {
            if (msSqlConfigration == null)
                throw new ArgumentNullException("msSqlConfigration");

            _msSqlConfigration = msSqlConfigration;
        }

        #region IChecker Members

        public bool CheckOut()
        {
            string connectionString = string.Format("Data Source={0};Initial Catalog={1};UserId={2};Password={3}", _msSqlConfigration.Host, _msSqlConfigration.DatabaseName, _msSqlConfigration.UserName, _msSqlConfigration.Password);
            var sqlConnection = new SqlConnection(connectionString);
            bool hasError = false;

            try
            {
                sqlConnection.Open();
            }
            catch (SqlException ex)
            {
                hasError = true;
                _logs = ex.Message;
            }
            finally
            {
                sqlConnection.Close();
                sqlConnection.Dispose();
            }

            return !hasError;
        }

        public string GetLogs()
        {
            return _logs;
        }

        #endregion
    }
}
